<template>
  <div class="main user-layout-register">
    <div v-if="!state.spinning" class="register-container">
      <h3 style="margin:36px 50px 0px 50px;">
        <span style="font-size: 24px;">注册</span>
        <router-link
          class="login"
          :to="{ name: 'login' }"
          style="font-size: 14px;color: #333333;font-family: PingFangSC-Regular;"
        >
          已有账号,去登录</router-link
        >
      </h3>
      <a-form id="formRegister" ref="formRegister" :form="form" @submit="handleSubmit">
        <a-form-item>
          <a-input
            v-decorator="[
              'username',
              {
                rules: [
                  {
                    required: true,
                    message: '请输入用户名'
                  }
                ],
                validateTrigger: ['change', 'blur']
              }
            ]"
            size="large"
            type="text"
            placeholder="请设置您的用户名"
          ></a-input>
        </a-form-item>

        <a-popover
          v-model="state.passwordLevelChecked"
          placement="rightTop"
          :trigger="['focus']"
          :getPopupContainer="trigger => trigger.parentElement"
        >
          <template slot="content">
            <div :style="{ width: '240px' }">
              <div :class="['user-register', passwordLevelClass]">
                强度：<span>{{ passwordLevelName }}</span>
              </div>
              <a-progress :percent="state.percent" :showInfo="false" :strokeColor="passwordLevelColor" />
              <div style="margin-top: 10px;">
                <span>请至少输入 6 个字符。请不要使用容易被猜到的密码。</span>
              </div>
            </div>
          </template>
          <a-form-item>
            <a-input-password
              v-decorator="[
                'password',
                {
                  rules: [
                    { required: true, message: '至少6位密码，区分大小写' },
                    { validator: this.handlePasswordLevel }
                  ],
                  validateTrigger: ['change', 'blur']
                }
              ]"
              size="large"
              placeholder="请设置您的登录密码"
              @blur="handlePasswordInputBlur"
              @click="handlePasswordInputClick"
            ></a-input-password>
          </a-form-item>
        </a-popover>

        <a-form-item>
          <a-input-password
            v-decorator="[
              'password2',
              {
                rules: [
                  { required: true, message: '至少6位密码，区分大小写' },
                  { validator: this.handlePasswordCheck }
                ],
                validateTrigger: ['change', 'blur']
              }
            ]"
            size="large"
            placeholder="请再次输入您的登录密码"
            @blur="handleConfirmBlur"
          ></a-input-password>
        </a-form-item>

        <a-form-item>
          <a-input
            v-decorator="[
              'mobile',
              {
                rules: [
                  { required: true, message: '请输入正确的手机号', pattern: /^1[3456789]\d{9}$/ },
                  { validator: this.handlePhoneCheck }
                ],
                validateTrigger: ['change', 'blur']
              }
            ]"
            size="large"
            placeholder="请输入您的手机号"
          ></a-input>
        </a-form-item>

        <a-form-item>
          <a-input
            v-decorator="['captcha', { rules: [{ required: true, message: '请输入验证码' }], validateTrigger: 'blur' }]"
            size="large"
            type="text"
            placeholder="请输入手机验证码"
          >
            <a-button
              slot="suffix"
              style=""
              class="getCaptcha"
              size="large"
              :disabled="state.smsSendBtn"
              @click.stop.prevent="getCaptcha"
              v-text="(!state.smsSendBtn && '获取验证码') || state.time + ' s'"
            ></a-button>
          </a-input>
        </a-form-item>

        <a-form-item>
          <a-button
            size="large"
            type="primary"
            htmlType="submit"
            class="register-button"
            :loading="registerBtn"
            :disabled="registerBtn"
            @click.stop.prevent="handleSubmit"
            >同意条款并注册
          </a-button>
        </a-form-item>
        <a-form-item style="margin-top:8px;font-size:0;">
          <a-checkbox
            v-decorator="[
              'agree',
              {
                rules: [{ required: true, message: '请勾选是否同意' }],
                validateTrigger: 'blur',
                valuePropName: 'checked'
              }
            ]"
            style="color: rgba(51, 51, 51, 0.51);padding-right:0px;"
          >
            我已阅读并同意条款
            <a herf class="login-tips" style="color:rgba(51, 51, 51, 0.51);">《法律证明和隐私政策》</a>
          </a-checkbox>
        </a-form-item>
      </a-form>
    </div>
    <div v-else>
      <a-spin tip="注册中" :spinning="state.spinning"></a-spin>
    </div>
  </div>
</template>

<script>
import { getSmsCaptcha, registerUser } from '@/api/login'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { deviceMixin } from '@/store/device-mixin'
import { timeFix } from '@/utils/util'

const levelNames = {
  0: '低',
  1: '低',
  2: '中',
  3: '强'
}
const levelClass = {
  0: 'error',
  1: 'error',
  2: 'warning',
  3: 'success'
}
const levelColor = {
  0: '#ff0000',
  1: '#ff0000',
  2: '#ff7e05',
  3: '#52c41a'
}
export default {
  name: 'Register',
  components: {},
  mixins: [deviceMixin],
  data() {
    return {
      form: this.$form.createForm(this),
      confirmDirty: true,
      state: {
        spinning: false,
        time: 60,
        smsSendBtn: false,
        passwordLevel: 0,
        passwordLevelChecked: false,
        percent: 10,
        progressColor: '#FF0000'
      },
      registerBtn: false
    }
  },
  computed: {
    passwordLevelClass() {
      return levelClass[this.state.passwordLevel]
    },
    passwordLevelName() {
      return levelNames[this.state.passwordLevel]
    },
    passwordLevelColor() {
      return levelColor[this.state.passwordLevel]
    }
  },
  watch: {
    'state.passwordLevel'(val) {
      console.log(val)
    }
  },
  methods: {
    handlePasswordLevel(rule, value, callback) {
      const form = this.form
      let level = 0

      // 判断这个字符串中有没有数字
      if (/[0-9]/.test(value)) {
        level++
      }
      // 判断字符串中有没有字母
      if (/[a-zA-Z]/.test(value)) {
        level++
      }
      // 判断字符串中有没有特殊符号
      if (/[^0-9a-zA-Z_]/.test(value)) {
        level++
      }
      this.state.passwordLevel = level
      this.state.percent = level * 30
      if (level >= 2) {
        if (level >= 3) {
          this.state.percent = 100
        }
        callback()
      } else {
        if (level === 0) {
          this.state.percent = 10
        }
        callback(new Error('密码强度不够'))
      }
      // 首次密码的再确认
      if (value && this.confirmDirty) {
        form.validateFields(['password2'], { force: true })
      }
    },
    handleConfirmBlur(e) {
      const value = e.target.value
      this.confirmDirty = this.confirmDirty || !!value
    },
    handlePasswordCheck(rule, value, callback) {
      const password = this.form.getFieldValue('password')
      console.log('value', value)
      if (value === undefined) {
        callback(new Error('请输入密码'))
      }
      if (value && password && value.trim() !== password.trim()) {
        callback(new Error('两次密码不一致'))
      }
      callback()
    },

    handlePhoneCheck(rule, value, callback) {
      console.log('handlePhoneCheck, rule:', rule)
      console.log('handlePhoneCheck, value', value)
      console.log('handlePhoneCheck, callback', callback)

      callback()
    },

    handlePasswordInputClick() {
      this.state.passwordLevelChecked = true
      return
    },
    // 输入完密码取消悬浮
    handlePasswordInputBlur() {
      this.state.passwordLevelChecked = false
      return
    },
    handleSubmit() {
      const {
        form: { validateFields },
        state
      } = this

      validateFields({ force: true }, (err, values) => {
        if (!err) {
          state.spinning = true
          const loginParams = {}
          loginParams.username = values.username
          loginParams.password = values.password
          // 昵称
          loginParams.name = values.username
          loginParams.phone = values.mobile
          loginParams.messageCode = values.captcha
          console.log('login form', loginParams)
          registerUser(loginParams)
            .then(res => {
              state.spinning = false
              if (res.data && res.data.accessToken) {
                this.loginSuccess(res)
              }
            })
            .catch(err => this.requestFailed(err))
            .finally(() => {
              state.registerBtn = false
            })
        }
      })
    },
    getCaptcha(e) {
      e.preventDefault()
      const {
        form: { validateFields },
        state,
        $message,
        $notification
      } = this

      validateFields(['mobile'], { force: true }, (err, values) => {
        if (!err) {
          state.smsSendBtn = true

          const interval = window.setInterval(() => {
            if (state.time-- <= 0) {
              state.time = 60
              state.smsSendBtn = false
              window.clearInterval(interval)
            }
          }, 1000)

          const hide = $message.loading('验证码发送中..', 0)

          getSmsCaptcha({ mobile: values.mobile })
            .then(res => {
              setTimeout(hide, 2500)
              console.log(res)
              $notification['success']({
                message: '提示',
                description: '验证码获取成功,请及时查看!',
                duration: 8
              })
            })
            .catch(err => {
              setTimeout(hide, 1)
              clearInterval(interval)
              state.time = 60
              state.smsSendBtn = false
              this.requestFailed(err)
            })
        }
      })
    },
    loginSuccess(res) {
      console.log(res)
      const accessToken = res.data.accessToken || ''
      storage.set(ACCESS_TOKEN, accessToken, 7 * 24 * 60 * 60 * 1000)
      // 延迟 1 秒显示欢迎信息
      setTimeout(() => {
        this.$router.push({ path: '/home' })
        this.$notification.success({
          message: '欢迎',
          description: `${timeFix()}，欢迎回来`
        })
      }, 1000)
      this.isLoginError = false
    },
    requestFailed(err) {
      this.$notification['error']({
        message: '错误',
        description: ((err.response || {}).data || {}).message || '请求出现错误，请稍后再试',
        duration: 4
      })
      this.registerBtn = false
    }
  }
}
</script>
<style lang="less">
.user-register {
  &.error {
    color: #ff0000;
  }

  &.warning {
    color: #ff7e05;
  }

  &.success {
    color: #52c41a;
  }
}

.user-layout-register {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .register-container {
    width: 420px;
    min-height: 498px;
    background-color: #feffff;
    box-shadow: 2px 1px 18px -2px #e0ecff;
    border-radius: 1px;
  }
  #formRegister {
    width: 321px;
    min-height: 427px;
    text-align: center;
    margin-left: 50px;
    margin-top: 18px;
    .ant-form-item {
      margin-bottom: 0px;
    }
  }

  .ant-input {
    position: relative;
    text-align: left;
    height: 42px;
    border-radius: 2px;
    margin-bottom: 12px;
    border: solid 1px #e5e6e9;
    background-color: #feffff;
  }
  /*密码是否显示*/
  .ant-input-password-icon {
    display: none;
  }

  .ant-input:placeholder-shown {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    font-weight: normal;
    font-stretch: normal;
    line-height: 14px;
    letter-spacing: 0px;
    color: rgba(51, 51, 51, 0.51);
  }
  .ant-input-group-lg .ant-select-selection--single {
    height: 42px;
  }
  .ant-input-group-addon:first-child {
    background-color: #fff;
    padding: 0;
  }
}
</style>
<style lang="less" scoped>
.user-layout-register {
  & > h3 {
    font-size: 16px;
    margin-bottom: 20px;
  }

  .getCaptcha {
    margin-right: -11px;
    margin-bottom: 12px;
    height: 40px;
    font-family: PingFangSC-Medium;
    font-size: 14px;
    line-height: 18px;
    letter-spacing: 0px;
    color: #33b0ed;
    border: none;
    box-shadow: none;
  }

  .register-button {
    width: 320px;
    height: 48px;
    background-color: #33b0ed;
    border-radius: 2px;
    margin-top: 18px;
  }
  /deep/ .ant-form-explain {
    text-align: left;
  }
  .login {
    float: right;
    line-height: 40px;
  }
}
</style>
